package com.woniu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.client.EmployClient;
import com.woniu.client.FlowClient;
import com.woniu.client.OrderClient;
import com.woniu.client.dto.*;
import com.woniu.comment.util.StateData;
import com.woniu.exception.RebornException;
import com.woniu.mapper.DepotDetialMapper;
import com.woniu.mapper.MonthTotalMapper;
import com.woniu.mapper.ReviewMapper;
import com.woniu.model.*;
import com.woniu.service.ReviewService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.aspectj.weaver.ast.Var;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  入库审核服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年05月23日
 */
@Service
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review> implements ReviewService {

    @Resource
    private ReviewMapper reviewMapper;
    @Resource
    private DepotDetialMapper depotDetialMapper;
    @Resource
    private OrderClient orderClient;
    @Resource
    private EmployClient employClient;
    @Resource
    private MonthTotalMapper monthTotalMapper;
    @Resource
    private FlowClient flowClient;

    /**
     * 确认入库
     * @param id 入库表ID
     * @throws RuntimeException 如果入库表不存在或已完成审核
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void confirmReview(Integer id,Integer handlerId) throws IOException {
        Review review = reviewMapper.selectById(id);
        System.out.println("查出来的review: "+ JSONUtil.parseObj(review));
        if (review == null) {
            throw new RebornException("不存在的入库表", 30001);
        }
        Integer state = review.getState();
        if (Objects.equals(state, StateData.INVENTORY_STATE_FINISH)) {
            throw new RebornException("无法操作已完成的入库审核", 30002);
        }
        review.setState(StateData.INVENTORY_STATE_FINISH);
        review.setStartTime(LocalDateTime.now());
        review.setStationId(review.getStationId());
        //负责人
        review.setAccountId(Long.valueOf(handlerId));
        System.out.println("修改后的review: "+ JSONUtil.parseObj(review));
        reviewMapper.updateById(review);
        //思考 入库审核后 要新增哪些东西? 1.仓库详情表 2.仓库每月统计表(盘存表) 3.流程控制表flowHandel
        //1.仓库详情表
        String orderDetail = review.getOrderDetail();//json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String, Object>> list = objectMapper.readValue(orderDetail, new TypeReference<List<Map<String, Object>>>() {
        });
        for (Map<String, Object> map : list) {
            //遍历生成仓库详情List
            DepotDetial depotDetail = new DepotDetial();
            depotDetail.setDepotId(Long.valueOf(review.getStationId()));
            depotDetail.setType(Long.parseLong(map.get("junkType").toString()));
            depotDetail.setNumber(new BigDecimal(map.get("number").toString()));
            depotDetail.setUnit(map.get("unit").toString());
            depotDetialMapper.insert(depotDetail);
        }
        //2.仓库每月统计表(盘存表)
        // 分组：根据废品小类将订单详情列表分组
        Map<Long, List<Map<String, Object>>> groupedByType = list.stream()
                .collect(Collectors.groupingBy(map -> Long.parseLong(map.get("junkType").toString())));

        // 遍历分组后的每个废品小类
        for (Map.Entry<Long, List<Map<String, Object>>> entry : groupedByType.entrySet()) {
            Long junkType = entry.getKey(); // 获取废品小类ID
            List<Map<String, Object>> items = entry.getValue(); // 获取对应废品小类的订单详情列表

            // 计算对应废品小类的总数量
            BigDecimal totalNumber = items.stream()
                    .map(item -> new BigDecimal(item.get("number").toString())) // 获取每个订单详情中的数量
                    .reduce(BigDecimal.ZERO, BigDecimal::add); // 将数量累加得到总数

            // 计算对应废品小类的总价格
            BigDecimal totalPrice = items.stream()
                    .map(item -> new BigDecimal(item.get("totalPrice").toString())) // 获取每个订单详情中的总价
                    .reduce(BigDecimal.ZERO, BigDecimal::add); // 将总价累加得到总价

            // 创建一个新的 MonthTotal 对象
            MonthTotal monthTotal = new MonthTotal();

            // 设置属性值
            monthTotal.setStationId(Long.valueOf(review.getStationId())); // 设置站点ID
            monthTotal.setType(junkType); // 设置废品小类ID
            monthTotal.setNumber(totalNumber); // 设置总数量
            monthTotal.setUnit(items.get(0).get("unit").toString()); // 设置单位，这里假设所有订单详情的单位都一致，取第一个订单详情的单位
            monthTotal.setMonth(LocalDateTime.now().getMonthValue()); // 设置当前月份
            monthTotal.setYear(LocalDateTime.now().getYear()); // 设置当前年份
            monthTotal.setTotalPrice(totalPrice); // 设置总价格

            // 将生成的 MonthTotal 对象插入到数据库中
            monthTotalMapper.insert(monthTotal);

            // 3.流程控制表flowHandel
            AddHandelDto addHandelDto = new AddHandelDto();
            //这里不填,下一步是用户评价 addHandelDto.setHandler(null);
            addHandelDto.setFlowCode(9);//订单完成
            addHandelDto.setFlowModeId(1);//废品回收流程
            addHandelDto.setOrderNum(review.getOrderNum());//设置订单编号
            addHandelDto.setMessage("订单已完成");
            //将生成的流程处理对象插入到数据库中
            Result<FlowHandleDto> add = flowClient.add(addHandelDto);
            if (add.getCode()!=200){
                throw new RebornException(add.getMessage(),add.getCode());
            }
        }
    }
    /**
     * 查询一个站点所有的入库审核记录
     * id:站点id
     */
    @Override
    public Page<Review> getPageById(Integer id, Integer pageNum, Integer pageSize) {
        // 默认分页参数处理
        pageNum = (pageNum == null) ? 1 : pageNum;
        pageSize = (pageSize == null) ? 3 : pageSize;

        // 创建分页对象
        Page<Review> page = new Page<>(pageNum, pageSize);

        // 创建查询条件
        QueryWrapper<Review> wrapper = new QueryWrapper<>();
        wrapper.eq("station_id", id);

        // 执行分页查询
        Page<Review> reviewPage = reviewMapper.selectPage(page, wrapper);

        // 检查结果是否为空
        if (reviewPage == null || reviewPage.getRecords().isEmpty()) {
            throw new RebornException("该站点不存在任何入库审核信息", 60001);
        }

        // 返回分页结果
        return reviewPage;
    }

    /**
     * 查询没有处理的
     * id:站点id
     */
    @Override
    public Page<Review> getUnHandelPageById(Integer id, Integer pageNum, Integer pageSize) {
        // 默认分页参数处理
        pageNum = (pageNum == null) ? 1 : pageNum;
        pageSize = (pageSize == null) ? 3 : pageSize;

        // 创建分页对象
        Page<Review> page = new Page<>(pageNum, pageSize);

        // 创建查询条件
        QueryWrapper<Review> wrapper = new QueryWrapper<>();
        wrapper.eq("station_id", id);
        wrapper.eq("state",StateData.REVIEW_STATE_WAITING);

        // 执行分页查询
        Page<Review> reviewPage = reviewMapper.selectPage(page, wrapper);

        // 检查结果是否为空
        if (reviewPage == null || reviewPage.getRecords().isEmpty()) {
            throw new RebornException("该站点没有待审核信息", 60001);
        }

        // 返回分页结果
        return reviewPage;
    }

    /**
     * 传入订单号 生成订单入库表
     * @param orderNum 订单号
     */
    @Override
    public void add(String orderNum) throws JsonProcessingException {
        Result<OrderDto> result = orderClient.findById(orderNum);
        if (result.getCode()!=200){
            throw new RebornException(result.getMessage(),result.getCode());
        }
        OrderDto orderDto = result.getData();

        if (orderDto==null){
            throw new RebornException("不存在的订单",60001);
        }
        Result<EmployDto> result1 = employClient.byId(orderDto.getEmployId().intValue());
        if (result1.getCode()!=200){
            throw new RebornException(result1.getMessage(),result1.getCode());
        }
        EmployDto employDto = result1.getData();
        Review review = new Review();
        review.setOrderNum(orderNum);
        review.setStaffId(employDto.getId());
        review.setStaffName(employDto.getEmployeName());
        review.setStaffName(orderDto.getName());
        review.setStationId(Math.toIntExact(employDto.getStationId()));
        Result<List<OrderDetailsDto>> result2 = orderClient.selectAllOrderDetailByOrderId(orderNum);
        if (result2.getCode()!=200) {
            throw new RebornException(result2.getMessage(),result2.getCode());
        }
        List<OrderDetailsDto> data = result2.getData();
        if (data==null||data.isEmpty()){
            throw new RebornException("不存在的垃圾详情表",40001);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        //转成json字符串
        String jsonData = objectMapper.writeValueAsString(data);
        review.setOrderDetail(jsonData);
        System.out.println(JSONUtil.toJsonStr(review));
        reviewMapper.insert(review);
    }
}

